package com.globant.scrollbar;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private static final int NOTIFICATION_ID = 0;
	
	private ProgressBar progressBar;
	private TextView progressNumber;
	private Button executeButton;
	private AsyncProcess asyncProcess;
	
	private void initialState() {
		progressBar = (ProgressBar)findViewById(R.id.progressBar);
        progressBar.setVisibility(ProgressBar.INVISIBLE);
        progressBar.setProgress(0);
        
        executeButton = (Button)findViewById(R.id.executeButton);
        executeButton.setEnabled(Boolean.TRUE);
        
        progressNumber = (TextView)findViewById(R.id.progress);
        progressNumber.setVisibility(ProgressBar.INVISIBLE);
        progressNumber.setText("0%");
	}
	
	private void finalState() {
        progressBar = (ProgressBar)findViewById(R.id.progressBar);
        progressBar.setVisibility(ProgressBar.VISIBLE);
 
        executeButton = (Button)findViewById(R.id.executeButton);
        executeButton.setEnabled(Boolean.FALSE);
        
        progressNumber = (TextView)findViewById(R.id.progress);
        progressNumber.setVisibility(ProgressBar.VISIBLE);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        if(getIntent() != null && getIntent().getExtras() != null 
        		&& getIntent().getExtras().containsKey(BusinessSettings.PROGRESS)) {
        	NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        	notificationManager.cancel(NOTIFICATION_ID);
        	
        	this.finalState();
        	int progress = getIntent().getExtras().getInt(BusinessSettings.PROGRESS);
            progressBar.setProgress(progress);
            progressNumber.setText(String.valueOf(progress).concat("%"));
            
        } else if(savedInstanceState != null && savedInstanceState.containsKey(BusinessSettings.PROGRESS)) {
        	this.finalState();
        	int progress = savedInstanceState.getInt(BusinessSettings.PROGRESS);
            progressBar.setProgress(progress);
            progressNumber.setText(String.valueOf(progress).concat("%"));
        } else {
        	this.initialState();
        }

        asyncProcess = (AsyncProcess)getLastNonConfigurationInstance();
        WeakReference<MainActivity> activityMap = new WeakReference<MainActivity>(this);
        
        if (asyncProcess == null) {
        	asyncProcess = new AsyncProcess(activityMap);
        } else if(getIntent() == null || getIntent().getExtras() == null 
        		|| !getIntent().getExtras().containsKey(BusinessSettings.PROGRESS)) {
        	asyncProcess.attach(activityMap);
        	updateProgress(asyncProcess.getProgressStatus());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public Object onRetainNonConfigurationInstance() {
    	asyncProcess.detach();
    	return asyncProcess;
    }
    
    private void updateProgress(int progress) {
		progressBar.setProgress(progress);
		progressNumber.setText(String.valueOf(progress).concat("%"));
      }
    
    public void startScrollBar(View view) {
    	this.finalState();
    	asyncProcess.execute();     
    }
    
	public void generateToastMessage() {
		Context context = getApplicationContext();
        CharSequence text = getResources().getString(R.string.process_finished);
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
	}

	
	public void triggerNotification() {
		CharSequence title = getResources().getString(R.string.atention);
		CharSequence message = getResources().getString(R.string.process_finished);

		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(
				R.drawable.ic_dialog_green_flag, getResources().getString(R.string.new_message),
				System.currentTimeMillis());

		Intent notificationIntent = new Intent(this, MainActivity.class);
		
		notificationIntent.putExtra(BusinessSettings.PROGRESS, progressBar.getProgress());
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,
				notificationIntent, 0);

		notification.setLatestEventInfo(MainActivity.this, title, message,
				pendingIntent);
		notificationManager.notify(NOTIFICATION_ID, notification);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(BusinessSettings.PROGRESS, progressBar.getProgress());
	}
	
	private class AsyncProcess extends AsyncTask<Void, Void, Void> {
		
		private int progressStatus = 0;
		private MainActivity activity;
		
		public AsyncProcess(WeakReference<MainActivity> activity) {
			attach(activity);
		}

		protected void onPreExecute() {
			progressStatus = 0;
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			while (progressStatus < 100) {
				progressStatus = progressStatus + 1;
				SystemClock.sleep(5000);
				publishProgress();
			}
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Void... progress) {
			if(activity != null) {
				activity.updateProgress(progressStatus);
			}
		}
		
		@Override
		protected void onPostExecute(Void progress) {
			if(activity != null) {
				if(activity.hasWindowFocus()) {
					activity.generateToastMessage();
				} else {
					activity.triggerNotification();
				}
			}
		}
		
		public void detach() {
			activity = null;
		}

		public void attach(WeakReference<MainActivity> activity) {
			this.activity = activity.get();
		}

		public int getProgressStatus() {
			return progressStatus;
		}
	}
}

